<template>
  <van-field
    :model-value="displayValue"
    :label="field.label"
    :placeholder="field.placeholder || `请选择${field.label}`"
    :rules="field.rules"
    readonly
    @click="showPicker = true"
  />

  <van-popup v-model:show="showPicker" position="bottom">
    <van-picker
      :columns="columns"
      @confirm="onConfirm"
      @cancel="showPicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, computed } from "vue";

const props = defineProps({
  field: {
    type: Object,
    required: true,
  },
  modelValue: {
    type: [String, Number],
    default: "",
  },
  options: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue"]);

const showPicker = ref(false);
const displayValue = computed(() => {
  if (props.modelValue) {
    const option = props.options.find((opt) => opt.value === props.modelValue);
    return option ? option.label : props.modelValue;
  }
  return "";
});

const columns = computed(() =>
  props.options.map((item) => ({
    text: item.text || item.label,
    value: item.value,
  }))
);

const onConfirm = ({ selectedValues }) => {
  const value = selectedValues[0];
  emit("update:modelValue", value);
  showPicker.value = false;
};
</script>
